﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
//using System.Text;
using System.Management;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace SetIpWin
{


    public partial class Form1 : Form
    {




        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 返回ip文件当前程序目录路径
        /// </summary>
        /// <returns></returns>
        private string GetPath()
        {
            string ipPath;
            ipPath = Environment.CurrentDirectory + @"\ip.txt";
            return ipPath;
        }

        /// <summary>
        /// 获取本地连接设置显示到界面
        /// </summary>
        private void SetWinFormIP()
        {
            //获取本地连接ip 掩码 网关 DNS
            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface bendi in interfaces)
            {
                if (bendi.Name.ToString().Equals("以太网") && bendi.NetworkInterfaceType.ToString().Equals("Ethernet"))
                {
                    IPInterfaceProperties ip = bendi.GetIPProperties();
                    //获取Ip 掩码
                    for (int i = 0; i < ip.UnicastAddresses.Count; i++)
                    {
                        //不插网线会得到一个保留地址 169.254.126.164
                        if (ip.UnicastAddresses[i].Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            if (ip.UnicastAddresses[i].Address != null)
                                textBox1.Text = ip.UnicastAddresses[i].Address.ToString();
                            //如果不插网线 获取不了掩码 返回null 
                            if (ip.UnicastAddresses[i].IPv4Mask != null)
                                textBox2.Text = ip.UnicastAddresses[i].IPv4Mask.ToString();
                        }
                    }
                    //获取网关
                    if (ip.GatewayAddresses.Count > 0)
                        textBox3.Text = ip.GatewayAddresses[0].Address.ToString();
                    //获取DNS     
                    //不要DnsAddresses[0].Address.ToString() 不正确 还有警告  “System.Net.IPAddress.Address”已过时:  
                    if (ip.DnsAddresses.Count > 0)
                        textBox4.Text = ip.DnsAddresses[0].ToString();
                    //备用DNS
                    if (ip.DnsAddresses.Count > 1)
                        textBox5.Text = ip.DnsAddresses[1].ToString();
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //开程序的时候判断有没有配置文件，没有的话创建一个
            StreamWriter sw;
            //不存在就新建一个文本文件,并在窗口显示目前IP
            if (!File.Exists(GetPath()))
            {

                sw = File.CreateText(GetPath());
                sw.Close();
                SetWinFormIP();
            }
            else
            {
                //如果存在就读数据到窗口
                sw = File.AppendText(GetPath());
                sw.Close();
                StreamReader fs = new StreamReader(GetPath());

                textBox1.Text = fs.ReadLine();
                textBox2.Text = fs.ReadLine();
                textBox3.Text = fs.ReadLine();
                textBox4.Text = fs.ReadLine();
                textBox5.Text = fs.ReadLine();
                fs.Close();
            }
        }

        public void button1_Click(object sender, EventArgs e)
        {

            //点设置的时候删除原来的配置文件，并且新创建一个
            File.Delete(GetPath());
            StreamWriter sw;
            sw = File.CreateText(GetPath());

            //把窗口的数据写入到文本

            sw.WriteLine(textBox1.Text, 1);
            sw.WriteLine(textBox2.Text, 1);
            sw.WriteLine(textBox3.Text, 1);
            sw.WriteLine(textBox4.Text, 1);
            sw.WriteLine(textBox5.Text, 1);
            sw.Close();

            //以下是设置IP的部分
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;

                //设置ip地址和子网掩码
                inPar = mo.GetMethodParameters("EnableStatic");
                inPar["IPAddress"] = new string[] { textBox1.Text };// 设置IP
                inPar["SubnetMask"] = new string[] { textBox2.Text };//设置子网掩码
                outPar = mo.InvokeMethod("EnableStatic", inPar, null);

                //设置网关地址
                inPar = mo.GetMethodParameters("SetGateways");
                inPar["DefaultIPGateway"] = new string[] { textBox3.Text };// 设置网关
                outPar = mo.InvokeMethod("SetGateways", inPar, null);

                //设置DNS
                inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                inPar["DNSServerSearchOrder"] = new string[] { textBox4.Text, textBox5.Text };// 1.DNS 2.备用DNS
                outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                break;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //以下是设置IP的部分
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;

                //设置ip地址和子网掩码
                inPar = mo.GetMethodParameters("EnableStatic");
                inPar["IPAddress"] = new string[] { "192.168.1.44" };// 设置IP
                inPar["SubnetMask"] = new string[] { textBox2.Text };//设置子网掩码
                outPar = mo.InvokeMethod("EnableStatic", inPar, null);

                //设置网关地址
                inPar = mo.GetMethodParameters("SetGateways");
                inPar["DefaultIPGateway"] = new string[] { "192.168.1.1" };// 设置网关
                outPar = mo.InvokeMethod("SetGateways", inPar, null);

                //设置DNS
                inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                inPar["DNSServerSearchOrder"] = new string[] { textBox4.Text, textBox5.Text };// 1.DNS 2.备用DNS
                outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                break;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //以下是设置IP的部分
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;

                //设置ip地址和子网掩码
                inPar = mo.GetMethodParameters("EnableStatic");
                inPar["IPAddress"] = new string[] { "192.168.3.44" };// 设置IP
                inPar["SubnetMask"] = new string[] { textBox2.Text };//设置子网掩码
                outPar = mo.InvokeMethod("EnableStatic", inPar, null);

                //设置网关地址
                inPar = mo.GetMethodParameters("SetGateways");
                inPar["DefaultIPGateway"] = new string[] { "192.168.3.1" };// 设置网关
                outPar = mo.InvokeMethod("SetGateways", inPar, null);

                //设置DNS
                inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                inPar["DNSServerSearchOrder"] = new string[] { textBox4.Text, textBox5.Text };// 1.DNS 2.备用DNS
                outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                break;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //以下是设置IP的部分
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;

                //设置ip地址和子网掩码
                inPar = mo.GetMethodParameters("EnableStatic");
                inPar["IPAddress"] = new string[] { "10.10.10.4" };// 设置IP
                inPar["SubnetMask"] = new string[] { "255.0.0.0" };//设置子网掩码
                outPar = mo.InvokeMethod("EnableStatic", inPar, null);

                //设置网关地址
                inPar = mo.GetMethodParameters("SetGateways");
                inPar["DefaultIPGateway"] = new string[] { "10.10.10.1" };// 设置网关
                outPar = mo.InvokeMethod("SetGateways", inPar, null);

                //设置DNS
                inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                inPar["DNSServerSearchOrder"] = new string[] { "10.10.10.1", "114.114.114.114" };// 1.DNS 2.备用DNS
                outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                break;
            }
        }


    }

}
